package com.fastjars.business.spring.http.servlet.wrapper;

import org.apache.commons.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * HttpServletRequestWrapper
 * 重写HttpServletRequestWrapper，过滤Xss攻击
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/03/21
 * @version 1.0.0
 */
public class HttpServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {
    private HttpServletRequest orgRequest = null;
    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request
     * @throws IllegalArgumentException if the request is null
     */
    public HttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.orgRequest = request;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(StringUtils.xssEncode(name));
        if(null != values){
            for(int i=0;i<values.length;i++){
                values[i] = StringUtils.xssEncode(values[i]);
            }
        }
        return values;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameterMap = super.getParameterMap();
        Map<String, String[]> map = null;
        if(parameterMap!=null){
            map = new HashMap<>();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                map.put(entry.getKey(), getParameterValues(entry.getKey()));
            }
        }
        return map;
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(StringUtils.xssEncode(name));
        if (value != null) {
            value = StringUtils.xssEncode(value);
        }
        return value;
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(StringUtils.xssEncode(name));
        if (value != null) {
            value = StringUtils.xssEncode(value);
        }
        return value;
    }

    /**
     * 获取最原始的request
     * @return
     */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }

    /**
     * 获取最原始的request的静态方法
     * @return
     */
    public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
        if (req instanceof HttpServletRequestWrapper) {
            return ((HttpServletRequestWrapper) req).getOrgRequest();
        }
        return req;
    }
}
